const THREAD_COUNT = navigator.hardwareConcurrency || 4; // 线程数，多线程分片文件
// 设置文件分片大小为5MB
const CHUNK_SIZE = 1024 * 1024 * 5;

export async function cutFile(file) {
    return new Promise((resolve) => {
        const result = [];
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE);
        // 线程完成数量
        let finishCount = 0;
        // 分片总数
        const workerChunkCount = Math.ceil(chunkCount / THREAD_COUNT);
        // 多线程分片
        for(let i = 0; i < THREAD_COUNT; i++){
            const worker = new Worker('/js/worker.js', {
                type: 'module'
            })
            // 计算每个线程的分片开始索引和结束索引
            const startIndex = i * workerChunkCount;
            let endIndex = startIndex + workerChunkCount;
            endIndex = endIndex > chunkCount ? chunkCount : endIndex;
            // 发送消息
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startIndex,
                endIndex
            });
            // 收到消息
            worker.onmessage = (e) => {
                for(let i = startIndex; i < endIndex; i++) {
                    result[i] = e.data[i - startIndex];
                }
                // 线程完成
                worker.terminate();
                // 完成线程数
                finishCount++;
                if(finishCount === THREAD_COUNT) {
                    resolve(result);
                }
            };
        }
    });
}